package com.sanniu.interceptor;

import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.Ret;
import com.sanniu.common.Consts;
import com.sanniu.common.PermissionManager;
import com.sanniu.model.BaseRet;
import com.sanniu.model.User;
import com.sanniu.model.common.PublicAction;
import com.sanniu.service.UserService;
import io.jboot.Jboot;
import io.jboot.web.controller.JbootController;

import javax.json.Json;
import javax.json.JsonObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class PermissionInterceptor implements Interceptor {

    @Inject
    private UserService userService;

    public void intercept(Invocation inv) {
        System.out.println(inv.getControllerKey() + "_" + inv.getActionKey() + "_" + inv.getMethodName());
        if (PermissionManager.checkRequireToken(inv.getControllerKey().replace("/", "").toLowerCase(),
                inv.getMethodName().toLowerCase())) {
            JbootController controller = (JbootController) inv.getController();

            Object userId = controller.getJwtPara("userId");
            System.out.println(userId);
            if (userId == null) {
                //未登录
                if (controller.isAjaxRequest()) {
                    inv.getController().renderJson(BaseRet.fail(10001, "非法访问"));
                } else {
                    inv.getController().redirect("/user/login");
                }
                return;
            } else {
                User user = userService.findById(userId);
                System.out.println(user);
                controller.setJwtAttr(Consts.JWT_USERID, user.getId());
                inv.getController().setAttr("userInfo", user);
            }
        }
        inv.invoke();

    }
}
